package com.example.demo05.securityHandler;

import com.example.demo05.util.JsonResult;
import com.example.demo05.util.ResultCode;
import com.example.demo05.util.ResultTool;
import com.example.demo05.util.TurnJson;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class CustomizeAuthenticationEntryPoint  implements AuthenticationEntryPoint {
    /*
    需要在前台接收到“用户未登录”提示信息
    实现此类 并在WebSecurityConfig注入
    CustomizeAuthenticationEntryPoint 主要用来处理匿名用户访问无权限资源时的异常（未登录，登录状态过期失效)
     */



    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        log.info("Cookies:{}",httpServletRequest.getCookies());
        JsonResult result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
//        httpServletResponse.setContentType("text/json;Charset=utf-8");
//        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(result));
         TurnJson.JsonWrite(httpServletResponse,result);
    }
}
